<template>
  <div class="selectCourse" :class="{ uopenSelect: !open }">
    <div class="small" :class="{ small_open: !open }" @click="handleChangeOpen">
      {{ open ? "收起" : "展开" }}
    </div>
    <div class="selectCourse-head" v-show="open">
      <div class="selectCourse-content">
        <div class="name">
          {{
            userInfo.realName ||
            userInfo.nickName ||
            userInfo.email ||
            userInfo.regName
          }}
        </div>
        <div class="desc"></div>
      </div>
    </div>
    <el-tree
      :data="getMyTeachingCourses"
      :props="defaultProps"
      :load="loadNode"
      lazy
      accordion
      node-key="id"
      :default-expanded-keys="defaultExpandedKeys"
      @node-click="changeNodeTarget"
      ref="tree"
      v-loading="gettingCourseList || confirmLoading"
      :element-loading-text="gettingCourseList? '数据加载中' : ''"
      element-loading-spinner="el-icon-loading"
      v-show="open"
    >
      <div
        class="custom-tree-node"
        :class="{
          currSelectNode: node.id == currSelectNode.id,
          currSelectTaskGroup:
            currSelectTaskGroup && node.id == currSelectTaskGroup.id && node.level == 2,
          currSelectTask: currSelectTask && node.id == currSelectTask.id && node.level == 3,
        }"
        slot-scope="{ node, data }"
      >
        <img
          src="@/assets/images/tg.png"
          v-if="node.level === 2 && node.id !== currSelectTaskGroup.id"
          class="taskGroup_icon"
        />
        <img
          src="@/assets/images/tg_a.png"
          v-if="node.level === 2 && node.id === currSelectTaskGroup.id"
          class="taskGroup_icon"
        />
        <img
          src="@/assets/images/t.png"
          v-if="node.level === 3 && currSelectTask && node.id !== currSelectTask.id"
          class="task_icon"
        />
        <img
          src="@/assets/images/t_a.png"
          v-if="node.level === 3 && currSelectTask && node.id === currSelectTask.id"
          class="taskGroup_icon"
          style="height: 18px"
        />
        <span
          class="span_name"
          :title="data.name || 'no-name'"
          style="height: 18px"
          >{{ data.name || "no-name" }}
        </span>
      </div>
    </el-tree>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
      },
      currSelectNode: {},
      currSelectTaskGroup: {},
      currSelectTask: {},
      defaultExpandedKeys: [],
      isFirstRender: true,
      firstNode: null,
      open: true,
    };
  },
  props: {
    courseInfo: Object,
    myTeachingCourses: Array,
    studentList: Array,
    gettingStuList: Boolean,
    gettingCourseList: Boolean,
    confirmLoading: Boolean,
  },
  watch: {
    // myTeachingCourses() {
    //   if (this.isFirstRender && this.courseInfo.name) {
    //     this.$nextTick(() => {
    //       this.handleSetDefaultExpandedKeys();
    //     });
    //   }
    // },
    courseInfo() {
      if (
        this.isFirstRender &&
        this.myTeachingCourses.length &&
        !this.gettingStuList
      ) {
        this.$nextTick(() => {
          this.handleSetDefaultExpandedKeys();
        });
      }
    },
    studentList() {
      if (
        this.isFirstRender &&
        this.myTeachingCourses.length &&
        this.courseInfo.name
      ) {
        this.$nextTick(() => {
          this.handleSetDefaultExpandedKeys();
        });
      }
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    getMyTeachingCourses() {
      return this.myTeachingCourses;
    },
  },
  created() {
    if (
      this.isFirstRender &&
      this.myTeachingCourses.length &&
      this.courseInfo.name
    ) {
      this.$nextTick(() => {
        this.handleSetDefaultExpandedKeys();
      });
    }
  },
  methods: {
    // 加载节点的数据
    async loadNode(node, resolve) {
      // this.changeNodeTarget(node);
      if (node.level === 0 || node.level >= 3) return resolve([]);
      if (node.level > 1)
        return node.data.children
          ? resolve([...node.data.children])
          : resolve();
      if (node.level === 1) {
        // 当前页面是否第一次渲染
        const params = {
          id: node.data.courseID,
          currNo: node.data.currNo,
          courseID: node.data.courseID,
        }
        if (!params.id || !params.currNo || !params.courseID) return this.$antdMessage.error({content: '获取课程信息失败，请刷新后再试!'})
        let res = null;
        if (this.isFirstRender) {
          res = this.courseInfo
            ? this.courseInfo
            : await this.$parent.fetchCoursesDeital(params);
          this.isFirstRender = false;
        } else {
          // 如果在当前页面直接切换课程 则需要获取课程详情并返回
          // res = await this.$parent.fetchCoursesDeital(params);
        }
        if (res) {
          /**
           * 切换课程时，有时会一直显示加载动画并报错。(暂时定位问题到此处)
           * 添加是否为数组判断， 分解对象会出现此类错误
           * TypeError: Invalid attempt to destructure non-iterable instance.
           * In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
           */
          Array.isArray(res.children) ? resolve([...res.children]) : resolve([]);
          this.$emit("changeSelectCourse", res, true);
          this.firstNode = node;
          this.changeCurrSelectNode(node);
          const firstTaskGroupChidlren = node.childNodes[0];
          if (firstTaskGroupChidlren) {
            this.$nextTick(() => {
              firstTaskGroupChidlren.expand();
              this.currSelectTaskGroup = firstTaskGroupChidlren;
              this.changeCurrSelectTaskGroup(firstTaskGroupChidlren);
              this.handleSelectFirstChidlren(firstTaskGroupChidlren);
            });
          } else {
            this.currSelectTaskGroup = null;
            this.handleChangeTaskInfo();
          }
        } else resolve([]);
      }
    },
    // 选择了课程
    changeCurrSelectNode(item) {
      this.currSelectNode = item;
      if (this.firstNode !== item) {
        const node = item;
        this.$emit("changeSelectCourse", {
          currNo: node.data.currNo,
          courseID: node.data.courseID,
        });
        this.$nextTick(() => {
          this.firstNode.expand();
          node.expanded = false;
          node.loaded = false;
          node.isCurrent = false;
        });
      }
    },
    // 选择了任务组
    changeCurrSelectTaskGroup(item) {
      if (
        item?.isCurrent &&
        item?.expanded &&
        this.currSelectTaskGroup !== item
      ) {
        this.currSelectTaskGroup = item;
        this.handleSelectFirstChidlren(item);
      } else {
        this.currSelectTask.isCurrent = true;
      }
      this.currSelectTaskGroup = item;
    },
    // 选择了任务
    changeCurrSelectTask(item) {
      if (this.currSelectTask && this.currSelectTask !== item)
        this.currSelectTask.isCurrent = false;
      this.currSelectTask = item;
      this.handleChangeTaskInfo();
    },
    // 选择第一个子级节点
    handleSelectFirstChidlren(parent) {
      const node = parent.childNodes[0];
      if (node) {
        this.changeCurrSelectTask(node);
        this.$nextTick(() => {
          node.expand();
          node.loaded = true;
          node.isCurrent = true;
        });
      } else {
        this.currSelectTask = null;
        this.handleChangeTaskInfo();
      }
    },
    // 将当前点击的目标记录
    changeNodeTarget() {
      const node = this.$refs.tree.currentNode.node;
      if (node.level === 1) {
        this.changeCurrSelectNode(node);
      }
      if (node.level === 2) {
        this.changeCurrSelectTaskGroup(node);
        if (node.childNodes.length) {
          const firstNode = node.childNodes[0];
          this.$nextTick(() => {
            firstNode.expand();
            // firstNode.collapse()
          });
        }
      }
      if (node.level === 3) {
        this.currSelectTask.expanded = false;
        this.changeCurrSelectTask(node);
      }
    },
    // 设置默认展开课程
    handleSetDefaultExpandedKeys() {
      if (!this.isFirstRender) return;
      const findCurrCourse = this.getMyTeachingCourses.find(
        (item) => item.currNo == this.courseInfo.currNo
      );
      if (findCurrCourse && findCurrCourse?.$treeNodeId) {
        let findNode = this.$refs.tree.root.childNodes.find(
          (item) => item.data.$treeNodeId === findCurrCourse.$treeNodeId
        );
        // debugger
        if (findNode?.childNodes && !findNode.childNodes.length) {
          findNode.childNodes = this.courseInfo.children || [];
          this.$nextTick(() => {
            this.defaultExpandedKeys.push(findCurrCourse.$treeNodeId);
            findNode.expand();
            // 等待获取已经请求的课程详情并展开节点后再执行
            this.$nextTick(() => {
              this.isFirstRender = false;
            });
          });
        } else {
          // 重新初始化课程列表
          this.handleInitCourse();
        }
      } else {
        // 重新初始化课程列表
        this.handleInitCourse();
      }
    },
    handleInitCourse() {
      /**
       * 如果Element-Tree没有渲染
       * 重新设置我的课程列表的数据、课程信息的数据
       * 如果课程信息数据不存在则尝试获取课程信息数据
       */
      const parent = this.$parent;
      parent.handleInitMyCourseList();
      if (parent.courseInfo.name) {
        parent.courseInfo = JSON.parse(JSON.stringify(parent.courseInfo));
      } else {
        parent.getCoursesDataNotEmpty();
      }
    },
    // 将当前选择的课程、任务组、任务信息发送到父组件
    handleChangeTaskInfo() {
      this.$emit("handleChangeSelectTaskInfo", {
        taskGroup: this.currSelectTaskGroup,
        task: this.currSelectTask,
      });
    },
    handleChangeOpen() {
      this.open = !this.open;
    },
  },
};
</script>

<style lang="stylus">
.selectCourse {
  resize: auto;
  position: relative;
  margin-right: 5px;
  width: 200px;
  min-width: 165px;
  height: 746px;
  background-color: #ffffff;
  border-radius: 10px;
  overflow-y: auto;
  transition: width 0.2s linear;

  .small {
    opacity: 0;
    cursor: pointer;
    position: absolute;
    top: 50%;
    width: 18px;
    background: #fff;
    text-align: center;
    border-radius: 0 5px 5px 0;
    z-index: 9999;
    transition: all 0.1s linear;
  }

  .small_open {
    opacity: 1;
    border-radius: 5px 0 0 5px;
  }

  .selectCourse-head {
    margin-bottom: 5px;
    padding: 0 6px 0;
    height: 80px;

    .selectCourse-content {
      padding: 0 5px 12px;
      border-bottom: 1px dashed #707070;

      .name {
        font-family: Segoe UI;
        font-size: 2rem;
        color: #707070;
        overflow hidden
        text-overflow: ellipsis
      }

      .desc {
        height: 19px;
      }
    }
  }

  .custom-tree-node {
    display: flex;
    width: 100%;
    max-width: calc(100% - 25px);
    align-items: center;

    .span_name {
      display: inline-block;
      flex: 1;
      max-width: 100%;
      overflow: hidden;
      line-height: 1;
      white-space: nowrap;
      text-overflow: ellipsis;
      font-family: Roboto;
      font-size: 1rem;
      color: #707070;
    }
  }

  .el-tree-node {
    .el-tree-node {
      .el-tree-node__expand-icon {
        display: none;
      }
    }
  }

  .is-expanded {
    > .el-tree-node__content {
      // position: sticky;
      top: 0;
      background: rgba(204, 228, 255, 0.3) !important;
      z-index: 998;
    }

    .el-tree-node__children {
      .el-tree-node__content {
        position: relative;
        top: 0;
        background: rgba(204, 228, 255, 0.3) !important;
        z-index: 997 !important;
      }
    }

    .is-expanded {
      background: rgba(204, 228, 255, 0.6) !important;

      .is-expanded {
        background: unset !important;
      }

      .is-current {
        background: #B3D7FF !important;
      }

      .is-expanded:focus {
        background: #B3D7FF !important;
      }
    }

    .is-expanded:focus {
      background: rgba(204, 228, 255, 0.3) !important;
    }
  }

  .taskGroup_icon {
    object-fit: scale-down;
    margin-right: 5px;
    width: 19px;
    height: 14px;
  }

  .task_icon {
    object-fit: scale-down;
    margin-right: 5px;
    width: 17px;
    height: 20px;
  }
}

.selectCourse:hover {
  .small {
    opacity: 1;
  }
}

.uopenSelect {
  min-width: 20px;
  width: 20px;
  background: transparent;
}

.selectCourse::-webkit-scrollbar {
  cursor: pointer;
  width: 4px;
  height: 1px;
}

/* 定义滚动条的滑块的样式有圆角和阴影以及自定义的背景色 */
.selectCourse::-webkit-scrollbar-thumb {
  -webkit-box-shadow: inset 0 0 1px rgba(195, 197, 198, 0.1);
  background: #ccc;
  border-radius: 10px;
}

/* 定义滚动条所在轨道的样式。有圆角和阴影以及淡色系的背景色 */
.selectCourse::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 1px rgba(195, 197, 198, 0.1);
  border-radius: 4px;
}
</style>